package com.zhu.transform.util;

import com.alibaba.fastjson.JSON;
import com.zhu.transform.bean.*;
import com.zhu.transform.exception.BaseException;
import com.zhu.transform.myenum.LogType;
import com.zhu.transform.myenum.MyExceptionType;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yingzhi zhu
 * date 2017/11/15.
 */
public class UtilInterfaceImpl implements UtilInterface {
    /**
     * 配置信息
     */
    private ConfBean confBean;
    /**
     * 支付方式json数据
     */
    private static String payMethodJson = "{\"status\":\"success\",\"data\":[{\"orignCode\":\"1\",\"code\":\"payCode_1\",\"name\":\"现金\"},{\"orignCode\":\"2\",\"code\":\"payCode_2\",\"name\":\"储值卡\"},{\"orignCode\":\"3\",\"code\":\"payCode_3\",\"name\":\"银联\"},{\"orignCode\":\"4\",\"code\":\"payCode_4\",\"name\":\"次卡\"},{\"orignCode\":\"6\",\"code\":\"payCode_6\",\"name\":\"网店现金\"},{\"orignCode\":\"7\",\"code\":\"payCode_7\",\"name\":\"网店会员储值\"},{\"orignCode\":\"8\",\"code\":\"payCode_8\",\"name\":\"网店支付宝\"},{\"orignCode\":\"9\",\"code\":\"payCode_9\",\"name\":\"积分兑换\"},{\"orignCode\":\"10\",\"code\":\"payCode_10\",\"name\":\"积分抵现\"},{\"orignCode\":\"11\",\"code\":\"payCode_11\",\"name\":\"店铺支付宝\"},{\"orignCode\":\"12\",\"code\":\"payCode_12\",\"name\":\"店铺京东支付\"},{\"orignCode\":\"13\",\"code\":\"payCode_13\",\"name\":\"店铺微信钱包支付\"},{\"orignCode\":\"34\",\"code\":\"payCode_34\",\"name\":\"银联-总公司预付卡\"},{\"orignCode\":\"35\",\"code\":\"payCode_35\",\"name\":\"银联-行业会员卡\"},{\"orignCode\":\"36\",\"code\":\"payCode_36\",\"name\":\"银联-行业积分通\"},{\"orignCode\":\"17\",\"code\":\"payCode_17\",\"name\":\"网店微信支付\"},{\"orignCode\":\"18\",\"code\":\"payCode_18\",\"name\":\"盒子支付\"},{\"orignCode\":\"19\",\"code\":\"payCode_19\",\"name\":\"购物卡\"},{\"orignCode\":\"20\",\"code\":\"payCode_20\",\"name\":\"收银通\"},{\"orignCode\":\"21\",\"code\":\"payCode_21\",\"name\":\"夏商IC卡\"},{\"orignCode\":\"22\",\"code\":\"payCode_22\",\"name\":\"夏商磁条卡\"},{\"orignCode\":\"23\",\"code\":\"payCode_23\",\"name\":\"通联支付\"},{\"orignCode\":\"24\",\"code\":\"payCode_24\",\"name\":\"拉卡拉\"},{\"orignCode\":\"14\",\"code\":\"payCode_14\",\"name\":\"微信支付\"},{\"orignCode\":\"15\",\"code\":\"payCode_15\",\"name\":\"店铺支付宝\"},{\"orignCode\":\"16\",\"code\":\"payCode_16\",\"name\":\"京东支付\"},{\"orignCode\":\"37\",\"code\":\"payCode_37\",\"name\":\"在线支付\"},{\"orignCode\":\"38\",\"code\":\"payCode_38\",\"name\":\"货到付款\"},{\"orignCode\":\"25\",\"code\":\"payCode_25\",\"name\":\"启航一卡通\"},{\"orignCode\":\"39\",\"code\":\"payCode_39\",\"name\":\"美团外卖\"},{\"orignCode\":\"40\",\"code\":\"payCode_40\",\"name\":\"饿了么外卖\"},{\"orignCode\":\"41\",\"code\":\"payCode_41\",\"name\":\"百度外卖\"},{\"orignCode\":\"42\",\"code\":\"payCode_42\",\"name\":\"旺POS银联卡\"},{\"orignCode\":\"43\",\"code\":\"payCode_43\",\"name\":\"旺POS支付宝\"},{\"orignCode\":\"44\",\"code\":\"payCode_44\",\"name\":\"旺POS微信\"},{\"orignCode\":\"45\",\"code\":\"payCode_45\",\"name\":\"民生银联卡\"},{\"orignCode\":\"46\",\"code\":\"payCode_46\",\"name\":\"民生支付宝\"},{\"orignCode\":\"47\",\"code\":\"payCode_47\",\"name\":\"民生微信\"},{\"orignCode\":\"48\",\"code\":\"payCode_48\",\"name\":\"预付卡\"},{\"orignCode\":\"49\",\"code\":\"payCode_49\",\"name\":\"通联银联卡\"},{\"orignCode\":\"50\",\"code\":\"payCode_50\",\"name\":\"通联支付宝\"},{\"orignCode\":\"51\",\"code\":\"payCode_51\",\"name\":\"通联微信\"},{\"orignCode\":\"52\",\"code\":\"payCode_52\",\"name\":\"通联百度钱包\"},{\"orignCode\":\"53\",\"code\":\"payCode_53\",\"name\":\"通联钱包\"},{\"orignCode\":\"54\",\"code\":\"payCode_54\",\"name\":\"预定金\"},{\"orignCode\":\"58\",\"code\":\"payCode_58\",\"name\":\"NETS\"},{\"orignCode\":\"72\",\"code\":\"payCode_72\",\"name\":\"pospalopenpay_pingan.微信.clientscanpos\"},{\"orignCode\":\"73\",\"code\":\"payCode_73\",\"name\":\"pospalopenpay_pingan.微信.posscanclient\"},{\"orignCode\":\"74\",\"code\":\"payCode_74\",\"name\":\"pospalopenpay_pingan.支付宝.clientscanpos\"},{\"orignCode\":\"75\",\"code\":\"payCode_75\",\"name\":\"pospalopenpay_pingan.支付宝.posscanclient\"},{\"orignCode\":\"76\",\"code\":\"payCode_76\",\"name\":\"pospalopenpay_wowo.微信.posscanclient\"},{\"orignCode\":\"77\",\"code\":\"payCode_77\",\"name\":\"pospalopenpay_wowo.支付宝.posscanclient\"},{\"orignCode\":\"78\",\"code\":\"payCode_78\",\"name\":\"pospalopenpay_swiftpass.微信.posscanclient\"},{\"orignCode\":\"79\",\"code\":\"payCode_79\",\"name\":\"pospalopenpay_swiftpass.支付宝.posscanclient\"},{\"orignCode\":\"80\",\"code\":\"payCode_80\",\"name\":\"pospalopenpay_swiftpass.微信.clientscanpos\"},{\"orignCode\":\"81\",\"code\":\"payCode_81\",\"name\":\"pospalopenpay_swiftpass.支付宝.clientscanpos\"},{\"orignCode\":\"82\",\"code\":\"payCode_82\",\"name\":\"pospalopenpay_royal.royalpay.posscanclient\"},{\"orignCode\":\"83\",\"code\":\"payCode_83\",\"name\":\"pospalopenpay_royal.royalpay.clientscanpos\"},{\"orignCode\":\"84\",\"code\":\"payCode_84\",\"name\":\"pospalopenpay_ums.银联支付.clientscanpos\"},{\"orignCode\":\"85\",\"code\":\"payCode_85\",\"name\":\"pospalopenpay_omi.omipay.clientscanpos\"},{\"orignCode\":\"86\",\"code\":\"payCode_86\",\"name\":\"pospalopenpay_ums2.银联支付.posscanclient\"},{\"orignCode\":\"87\",\"code\":\"payCode_87\",\"name\":\"pospalopenpay_allin.通联微信.posscanclient\"},{\"orignCode\":\"88\",\"code\":\"payCode_88\",\"name\":\"pospalopenpay_allin.通联支付宝.posscanclient\"},{\"orignCode\":\"89\",\"code\":\"payCode_89\",\"name\":\"pospalopenpay_allin.通联QQ支付.posscanclient\"},{\"orignCode\":\"90\",\"code\":\"payCode_90\",\"name\":\"pospalopenpay_dianking.微信.posscanclient\"},{\"orignCode\":\"91\",\"code\":\"payCode_91\",\"name\":\"pospalopenpay_dianking.支付宝.posscanclient\"},{\"orignCode\":\"92\",\"code\":\"payCode_92\",\"name\":\"pospalopenpay_allin.通联微信.clientscanpos\"},{\"orignCode\":\"93\",\"code\":\"payCode_93\",\"name\":\"pospalopenpay_allin.通联支付宝.clientscanpos\"},{\"orignCode\":\"94\",\"code\":\"payCode_94\",\"name\":\"pospalopenpay_allin.通联QQ支付.clientscanpos\"},{\"orignCode\":\"95\",\"code\":\"payCode_95\",\"name\":\"pospalopenpay_omi.omipay.posscanclient\"},{\"orignCode\":\"55\",\"code\":\"payCode_55\",\"name\":\"魔方微信\"},{\"orignCode\":\"56\",\"code\":\"payCode_56\",\"name\":\"魔方支付宝\"},{\"orignCode\":\"57\",\"code\":\"payCode_57\",\"name\":\"魔方银联支付\"},{\"orignCode\":\"59\",\"code\":\"payCode_59\",\"name\":\"魔方银联扫码\"},{\"orignCode\":\"-21\",\"code\":\"payCode_-21\",\"name\":\"pospalopenpay_uline.优畅微信.posscanclient\"},{\"orignCode\":\"-22\",\"code\":\"payCode_-22\",\"name\":\"pospalopenpay_uline.优畅支付宝.posscanclient\"},{\"orignCode\":\"-23\",\"code\":\"payCode_-23\",\"name\":\"pospalopenpay_uline.优畅微信.clientscanpos\"},{\"orignCode\":\"-24\",\"code\":\"payCode_-24\",\"name\":\"pospalopenpay_uline.优畅支付宝.clientscanpos\"},{\"orignCode\":\"-5\",\"code\":\"payCode_-5\",\"name\":\"pospalopenpay_cmbc.民生银行微信.posscanclient\"},{\"orignCode\":\"-6\",\"code\":\"payCode_-6\",\"name\":\"pospalopenpay_cmbc.民生银行支付宝.posscanclient\"},{\"orignCode\":\"-7\",\"code\":\"payCode_-7\",\"name\":\"pospalopenpay_cmbc.民生银行微信.clientscanpos\"},{\"orignCode\":\"-8\",\"code\":\"payCode_-8\",\"name\":\"pospalopenpay_cmbc.民生银行支付宝.clientscanpos\"},{\"orignCode\":\"-9\",\"code\":\"payCode_-9\",\"name\":\"pospalopenpay_xdd.享多多微信.posscanclient\"},{\"orignCode\":\"-10\",\"code\":\"payCode_-10\",\"name\":\"pospalopenpay_xdd.享多多支付宝.posscanclient\"},{\"orignCode\":\"-11\",\"code\":\"payCode_-11\",\"name\":\"pospalopenpay_xdd.享多多微信.clientscanpos\"},{\"orignCode\":\"-12\",\"code\":\"payCode_-12\",\"name\":\"pospalopenpay_xdd.享多多支付宝.clientscanpos\"},{\"orignCode\":\"-13\",\"code\":\"payCode_-13\",\"name\":\"pospalopenpay_tengzone.腾云宝微信.clientscanpos\"},{\"orignCode\":\"-14\",\"code\":\"payCode_-14\",\"name\":\"pospalopenpay_tengzone.腾云宝支付宝.clientscanpos\"},{\"orignCode\":\"-15\",\"code\":\"payCode_-15\",\"name\":\"pospalopenpay_sinopaypal.翔融微信.posscanclient\"},{\"orignCode\":\"-16\",\"code\":\"payCode_-16\",\"name\":\"pospalopenpay_sinopaypal.翔融支付宝.posscanclient\"},{\"orignCode\":\"-17\",\"code\":\"payCode_-17\",\"name\":\"pospalopenpay_sinopaypal.翔融微信.clientscanpos\"},{\"orignCode\":\"-18\",\"code\":\"payCode_-18\",\"name\":\"pospalopenpay_sinopaypal.翔融支付宝.clientscanpos\"},{\"orignCode\":\"102\",\"code\":\"payCode_102\",\"name\":\"支 付 宝\"},{\"orignCode\":\"103\",\"code\":\"payCode_103\",\"name\":\"其它\"},{\"orignCode\":\"104\",\"code\":\"payCode_104\",\"name\":\"美团\"}]}";
    /**
     * 保存目录
     */
    private static String saveFold = "dataBack";
    /**
     *
     */
    private static String tempFold = "temp";
    /**
     * 开始时间
     */
    private  String endTime = "";
    /**
     * 结束时间
     */
    private  String startTime = "";

    @Override
    public ConfBean initConf() {
        try {
            InputStream inputStream = null;
            inputStream = new FileInputStream("conf.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            confBean = new ConfBean();
            String ignoreStart = "##";
            //逐行读取配置文件
            reader.lines().forEach(item->{
                if (!item.startsWith(ignoreStart) && !"".equals(item) && item.split("=").length>1){
                    String key = item.split("=")[0];
                    String value = item.split("=")[1];
                    //配置文件属性动态注入到配置对象中
                    ZhuUtil.dynamicInjectValue(confBean,key,value);
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("配置文件读取错误");
        }
        return confBean;
    }

    @Override
    public List<RespBean> requestData() throws BaseException {
        List<RespBean> resultList = null;
        try {
            boolean queryNextPage = true;
            endTime = ZhuUtil.getNowTime();
            startTime = ZhuUtil.getTodayStartTime();
            RequestBodyBean requestBodyBean = new RequestBodyBean(confBean.getAppid(), startTime,
                    endTime);
            resultList = new ArrayList<>();
            while (queryNextPage) {
                //签名
                String dataSignature = Md5Util.encryptToMd5String(JSON.toJSONString(requestBodyBean), confBean.getAppKey());
                //请求数据
                String jsonResult = HttpUtil.post(confBean.getRequestOrderUrl(),
                        JSON.toJSONString(requestBodyBean), String.valueOf(System.currentTimeMillis()), dataSignature);
                //对返回的JSON数据格式化

                RespBean respBean = JSON.parseObject(jsonResult, RespBean.class);
                //添加到返回结果集
                resultList.add(respBean);
                //最大的返回条目数
                int maxQuerySize = respBean.getData().getPageSize();
                //实际的返回条目数
                int realQuerySize = respBean.getData().getResult().size();
                //如果  查询的订单大于真实的订单 则需要查询下一页
                queryNextPage = !(maxQuerySize > realQuerySize);
                //设置下次查询的分页数
                requestBodyBean.setPostBackParameter(respBean.getData().getPostBackParameter());
            }
        }  catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();

            throw new BaseException("请求或解析json数据的时候竟然出错了","",MyExceptionType.RequestData);
        }
        return resultList;
    }

    @Override
    public List<RespBean> requestData(String startTime,String endTime) throws BaseException {
        List<RespBean> resultList = null;
        this.startTime = startTime;
        this.endTime = endTime;
        try {
            boolean queryNextPage = true;
            RequestBodyBean requestBodyBean = new RequestBodyBean(confBean.getAppid(), startTime,
                    endTime);
            resultList = new ArrayList<>();
            while (queryNextPage) {
                //签名
                String dataSignature = Md5Util.encryptToMd5String(JSON.toJSONString(requestBodyBean), confBean.getAppKey());
                //请求数据
                String jsonResult = HttpUtil.post(confBean.getRequestOrderUrl(),
                        JSON.toJSONString(requestBodyBean), String.valueOf(System.currentTimeMillis()), dataSignature);
                //对返回的JSON数据格式化
                RespBean respBean = JSON.parseObject(jsonResult, RespBean.class);
                //添加到返回结果集
                resultList.add(respBean);
                //最大的返回条目数
                int maxQuerySize = respBean.getData().getPageSize();
                //实际的返回条目数
                int realQuerySize = respBean.getData().getResult().size();
                //如果  查询的订单大于真实的订单 则需要查询下一页
                queryNextPage = !(maxQuerySize > realQuerySize);
                //设置下次查询的分页数
                requestBodyBean.setPostBackParameter(respBean.getData().getPostBackParameter());
            }
        }  catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();

            throw new BaseException("请求或解析json数据的时候竟然出错了","",MyExceptionType.RequestData);
        }
        return resultList;
    }
    int sn = 0;
    @Override
    public List<TargetBean> parseToTarget(List<RespBean> respBeanList) throws BaseException {
        List<TargetBean> targetBeanList = new ArrayList<>();
        try {
            sn = ZhuUtil.getLastSn();
        for (RespBean respBean : respBeanList) {

            respBean.getData().getResult().forEach(item -> {
                TargetBean targetBean = new TargetBean();
                targetBean.setNetamt(item.getTotalAmount());
                if ("SELL_RETURN".equals(item.getTicketType())){
                    targetBean.setNetamt("-"+item.getTotalAmount());
                }
                //设置支付方式
                item.getPayments().forEach(payment -> {
                    if (payMethodJson.contains("\"" + payment.getCode() + "\"")) {
//                        获取对应支付方式的支付名
                        String[] str = payMethodJson.split("\"" + payment.getCode() + "\",\"name\":\"");
                        String payName = str[1].substring(0, str[1].indexOf("\""));
                        targetBean.setcH("0.00");
                        targetBean.setcI("0.00");
                        targetBean.setcO("0.00");
                        targetBean.setOt("0.00");
                        targetBean.setVipcode(confBean.getVipcode());
                        //货号
                        targetBean.setPlu(confBean.getPlu());
                        //店铺号
                        targetBean.setStorecode(confBean.getStorecode());

                        targetBean.setTillid(confBean.getTillid());

                        //不考虑国外银行卡
                        if (payName.contains("现金")) {
                            //现金支付
                            targetBean.setcH(payment.getAmount());
                        } else if (payName.contains("银联")) {
                            //国内银行卡
                            targetBean.setcI(payment.getAmount());
                        } else {
                            //其他银行卡
                            targetBean.setOt(payment.getAmount());
                        }
                    }
                });
                //
                targetBean.setTtldiscount(ZhuUtil.getTtldiscount(item.getDiscount(), item.getTotalAmount(), item.getRounding()));

                //设置日期
                targetBean.setTxdate(ZhuUtil.getTimeByTimeAndFormat(item.getDatetime(), "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd"));
                //设置时间
                targetBean.setTxtime(ZhuUtil.getTimeByTimeAndFormat(item.getDatetime(), "yyyy-MM-dd HH:mm:ss", "HHmm"));
                //生成货号
                sn++;
                targetBean.setDocno(ZhuUtil.creatSn(sn));
                targetBeanList.add(targetBean);
            });
        }
            ZhuUtil.saveSnToFile(sn);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("银豹数据json转化格式的时候竟然出错了",JSON.toJSONString(respBeanList), MyExceptionType.ParseToTarget);
        }

        return targetBeanList;
    }

    @Override
    public String saveDataToFile(List<TargetBean> targetBeanList) throws BaseException {
        String filePath = "";
        StringBuffer targetTableStringBuffer = new StringBuffer();
        try {
        if (confBean.getShowTableHeader() == 1){
            targetTableStringBuffer.append("店铺号\t");
            targetTableStringBuffer.append("收银机号\t");
            targetTableStringBuffer.append("日期\t");
            targetTableStringBuffer.append("时间\t");
            targetTableStringBuffer.append("单据号\t");
            targetTableStringBuffer.append("销售货号\t");
            targetTableStringBuffer.append("VIP\t");
            targetTableStringBuffer.append("现金\t");
            targetTableStringBuffer.append("内卡\t");
            targetTableStringBuffer.append("外卡\t");
            targetTableStringBuffer.append("其他\t");
            targetTableStringBuffer.append("折扣\t");
            targetTableStringBuffer.append("总金额\r\n");
        }


        targetBeanList.forEach(item -> {

            targetTableStringBuffer.append(item.getStorecode()).append("\t");
            targetTableStringBuffer.append(item.getTillid()).append("\t");
            targetTableStringBuffer.append(item.getTxdate()).append("\t");
            targetTableStringBuffer.append(item.getTxtime()).append("\t");
            targetTableStringBuffer.append(item.getDocno()).append("\t");
            targetTableStringBuffer.append(item.getPlu()).append("\t");
            targetTableStringBuffer.append(item.getVipcode()).append("\t");
            targetTableStringBuffer.append(item.getcH()).append("\t");
            targetTableStringBuffer.append(item.getcI()).append("\t");
            targetTableStringBuffer.append(item.getcO()).append("\t");
            targetTableStringBuffer.append(item.getOt()).append("\t");
            targetTableStringBuffer.append(item.getTtldiscount()).append("\t");
            targetTableStringBuffer.append(item.getNetamt()).append("\r\n");


        });
        filePath = ZhuUtil.foldIsExist(saveFold,
                ZhuUtil.getTimeByTimeAndFormat(endTime, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH-mm-ss"), confBean.getSuffix());

            FileOutputStream outputStream = new FileOutputStream(ZhuUtil.foldIsExist(saveFold,
                    ZhuUtil.getTimeByTimeAndFormat(endTime, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH-mm-ss"), confBean.getSuffix()));
            outputStream.write(targetTableStringBuffer.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("目标数据保存成文件的时候竟然出错了",JSON.toJSONString(targetBeanList),MyExceptionType.SaveDataToFile);
        }

        return filePath;
    }

    @Override
    public void uploadToFtp(String filePath) throws BaseException {
        try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(confBean.getFtpUrl(), Integer.parseInt(confBean.getFtpPort()));
        ftpClient.login(confBean.getFtpUsername(), confBean.getFtpPassword());
        boolean isExist = ftpClient.changeWorkingDirectory(confBean.getFtpPath());
        if (!isExist){
            ftpClient.makeDirectory(confBean.getFtpPath());
        }
        ftpClient.changeWorkingDirectory(confBean.getFtpPath());
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //读取本地文件
        File file = new File(filePath);
        InputStream inputStream = new FileInputStream(file);
        //第一个参数是文件名
        ftpClient.storeFile(file.getName(), inputStream);
        inputStream.close();
        ftpClient.logout();
        ftpClient.disconnect();
        ZhuUtil.printLog("上传成功", LogType.INFO);
    } catch (Exception e) {
        e.printStackTrace();
        throw new BaseException("FTP上传的时候竟然错误了",filePath,MyExceptionType.UploadToFtp);
    }
    }

    @Override
    public String getPayMethod() {
        try {
        PayMethodRequest payMethodRequest = new PayMethodRequest(confBean.getAppid());
        //签名
        String dataSignature = Md5Util.encryptToMd5String(JSON.toJSONString(payMethodRequest), confBean.getAppKey());
        //请求数据
            return HttpUtil.post(confBean.getPayMethodUrl(),
                    JSON.toJSONString(payMethodRequest), String.valueOf(System.currentTimeMillis()), dataSignature);
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return payMethodJson;
    }

}
